from __future__ import print_function

import datetime
import time

import kubernetes.client
import zmail
from kubernetes.client.rest import ApiException

CLOUDNAME = "test"

"""
pip3 install kubernetes zmail
"""


def send_mail(subject, content):
    """
    :param subject: title of the mail
    :param content: content of the mail
    :return: None
    """
    print("sed e-mail: subject: %s" % subject)
    mail_content = {
        "subject": subject,
        "content": content
    }
    server = zmail.server('172**190@qq.com', '123')
    server.send_mail('172**190@qq.com', mail_content)


def main():
    # Configure API key authorization: BearerToken
    configuration = kubernetes.client.Configuration()
    configuration.api_key['authorization'] = '31ada4fd-adec-460c-809a-9e56ceb75269'
    # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
    configuration.api_key_prefix['authorization'] = 'Bearer'

    configuration.host = "https://172.16.8.30:6443"
    configuration.ssl_ca_cert = "/Users/ddy/172.16.8.30/ca.crt"

    # create an instance of the API class
    client = kubernetes.client.ApiClient(configuration)

    apis_api_instance = kubernetes.client.CoreV1Api(client)

    send_times = 0
    while True:
        try:
            nodes = apis_api_instance.list_node()
            for node in nodes.items:
                address = node.status.addresses[0].address
                print("\n node: %s" % address, end=', ')
                for condition in node.status.conditions:
                    print("%s: %s" % (condition.type, condition.status), end=', ')
                    title = "%s %s 's %s: %s" % (CLOUDNAME, address, condition.type, condition.status)
                    if condition.type == 'Ready':
                        # 过滤刚刚创建的node
                        creation_timestamp = node.metadata.creation_timestamp  # datetime类型
                        # print("creation_timestamp(utc time): ", creation_timestamp)
                        creation_timestamp_second = datetime.datetime.timestamp(creation_timestamp)  # 时间戳--秒
                        # print("creation at local time: ",
                        #       time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(creation_timestamp_second)))
                        if time.time() - creation_timestamp_second < 180:
                            continue
                        # 状态不是Ready
                        if condition.status == 'False':
                            send_mail(title, "")
                    else:
                        if condition.status == 'True':
                            send_mail(title, "")
        except ApiException as e:
            print("Exception when calling AuthenticationV1Api->create_token_review: %s\n" % e)
            if send_times < 3:
                send_mail("%s ApiException" % CLOUDNAME, e)
            send_times += 1
        print('')
        time.sleep(30)


if __name__ == '__main__':
    main()
